package com.corgi.formatter.util;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.runtime.RuntimeSchema;

/**
 * @title: ProtoBufUtil
 * @description:
 * @author: dengmiao
 * @create: 2019-11-06 20:01
 **/
public class ProtoBufUtil {

    // 不能是数组?
    public static <T> byte[] serializer(T t, Class<T> clazz) {
        return ProtobufIOUtil.toByteArray(t, RuntimeSchema.createFrom(clazz),
                LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
    }

    public static <T> T deserializer(byte[] bytes, Class<T> clazz) {
        RuntimeSchema<T> runtimeSchema = RuntimeSchema.createFrom(clazz);
        T t = runtimeSchema.newMessage();
        ProtobufIOUtil.mergeFrom(bytes, t, runtimeSchema);
        return t;
    }
}
